package io.xxx.omni.mdc.site.service

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import io.xxx.omni.mdc.model.Authorization
import io.xxx.omni.mdc.model.AuthorizationMapper
import io.xxx.omni.mdc.model.Platform
import io.xxx.omni.mdc.model.PlatformMapper
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cache.annotation.CacheConfig
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service

@Service
@CacheConfig(cacheNames = ["platforms"])
class PlatformService {

    private val log = LoggerFactory.getLogger(javaClass)

    @Autowired
    private lateinit var platformMapper: PlatformMapper

    @Autowired
    private lateinit var authorizationMapper: AuthorizationMapper

    @Cacheable
    fun getAll(enabled: Boolean?): List<Platform> {
        log.info("Platform getAll")
        val wrapper = KtQueryWrapper(Platform::class.java)
        if (enabled != null)
            wrapper.eq(Platform::enabled, enabled)
        val platforms = platformMapper.selectList(wrapper)

        val storeWrapper = KtQueryWrapper(Authorization::class.java)
            .`in`(Authorization::pid, platforms.map { it.id })
        val authorizations = authorizationMapper.selectList(storeWrapper)
            .groupBy { it.pid }

        for (platform in platforms)
            platform.authorizations = authorizations[platform.id] ?: emptyList()
        return platforms
    }

    @Cacheable
    fun getOne(id: String): Platform {
        log.info("Platform getOne: $id")
        return platformMapper.selectById(id)
    }
}